<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <!-- <template #color="{ model, field }"> -->
      <!-- <color-picker v-model:pureColor="model[field]" shape="square" useType="both" format="hex" /> -->
      <!-- <div id="colors">
          <Teleport to="#colors">
            <color-picker
              v-model:pureColor="model[field]"
              shape="circle"
              useType="both"
              format="hex"
            />
          </Teleport>
        </div> -->
      <!-- </template> -->
      <template #file>
        <template v-if="!isObjStoreEnabled">
          <Upload :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove">
            <Button>
              <upload-outlined />
              上传文件
            </Button>
          </Upload>
        </template>
        <template v-else>
          <Upload
            multiple
            :file-list="fileList"
            :before-upload="beforeUpload"
            @remove="handleRemove"
            @change="handleFilesChange"
          >
            <a-button class="mt-1.5">
              <UploadOutlined />
              上传文件
            </a-button>
            <template #itemRender="{ file, actions }">
              <template v-if="getAttVisible(file)">
                <div class="pt-2 w-350px flex justify-between">
                  <span :style="file.status === 'error' ? 'color: red' : ''">{{ file.name }}</span>
                  <span>
                    <Tooltip title="下载">
                      <DownloadOutlined
                        class="ml-2"
                        style="color: #0960bd"
                        v-if="getAttUploadFinished(file)"
                        @click="handleDownloadAtt(file)"
                      />
                    </Tooltip>
                    <Tooltip title="删除">
                      <DeleteOutlined
                        class="ml-2 mr-4"
                        @click="handleRemoveFile(file, actions)"
                        style="color: #ed6f6f"
                      />
                    </Tooltip>
                  </span>
                </div>
                <Progress :percent="getProgress(file)" />
              </template>
            </template>
          </Upload>
        </template>
      </template>
      <!-- v-model:pureColor="pureColor" 
          v-model:gradientColor="gradientColor"-->
      <template #realNames="{ model, field }">
        <div>
          <FormItemRest>
            <div class="mb-2" v-show="!isUpdate">
              <RadioGroup v-model:value="radioValue" button-style="solid">
                <RadioButton value="radioAll" @click="getRadioValue('radioAll')"
                  >全部用户</RadioButton
                >
                <RadioButton value="radioSelect" @click="getRadioValue('radioSelect')"
                  >选择用户</RadioButton
                >
              </RadioGroup>
            </div>
          </FormItemRest>
          <InputTextArea :disabled="true" :row="3" v-model:value="model[field]" />
        </div>
      </template>
    </BasicForm>
    <BasicTable @register="registerTable" v-show="oaNoticeAttList.length > 0">
      <template #action="{ record, index }">
        <TableAction
          :actions="[
            {
              icon: 'ion:download-outline',
              tooltip: '下载',
              onClick: handleDownload.bind(null, record),
              loading: record.isDownloadAtt ? true : false,
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record, index),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <SelectUser @register="registerModal" @success="handleModelSuccess" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import {
    UploadOutlined,
    DeleteOutlined,
    DownloadOutlined,
    PictureOutlined,
    ProfileOutlined,
  } from '@ant-design/icons-vue';
  import {
    Input,
    Radio,
    Form,
    Upload,
    Button,
    UploadProps,
    Progress,
    Tooltip,
  } from 'ant-design-vue';
  import { formSchema } from './notice.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { SelectUser } from '/@/components/CustomComp';
  import { useModal } from '/@/components/Modal';
  import { dateUtil, formatToDate } from '/@/utils/dateUtil';
  import { BasicColumn } from '/@/components/Table';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { downloadByData } from '/@/utils/file/download';
  import { useUserStore } from '/@/store/modules/user';
  import {
    getObjectByKey,
    uploadFileObjectFunc,
    deleteByUid,
    isUploadFinished,
  } from '/@/utils/uploadFile';
  import { useRouter } from 'vue-router';
  import { isImage, ajaxPost, myMsg, getServerInfo } from '/@/utils/utils';
  import { useUploadFileStore } from '/@/store/modules/uploadFile';
  import { useMessage } from '/@/hooks/web/useMessage';

  import {
    getNoticeAdd,
    getNoticeCreate,
    getNoticeEdit,
    getNoticeSave,
    getNoticeDelAtt,
    getNoticeAttDownload,
    getNoticeAttList,
  } from '/@/api/administration/administration';
  export default defineComponent({
    name: 'NoticeDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      SelectUser,
      RadioGroup: Radio.Group,
      RadioButton: Radio.Button,
      FormItemRest: Form.ItemRest,
      InputTextArea: Input.TextArea,
      Upload,
      Button,
      UploadOutlined,
      BasicTable,
      TableAction,
      Progress,
      DeleteOutlined,
      DownloadOutlined,
      PictureOutlined,
      ProfileOutlined,
      Tooltip,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = reactive({});
      let radioValue = ref('radioAll');
      const fileList = ref<UploadProps['fileList']>([]);
      const gradientColor = ref(
        'linear-gradient(0deg, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%)',
      );

      const userStore = useUserStore();
      const serverInfo = userStore.getServerInfo;
      const isObjStoreEnabled = ref(serverInfo.isObjStoreEnabled);
      const { currentRoute, replace, push } = useRouter();
      const { createMessage, createWarningModal } = useMessage();
      let tempAttList: any = [];
      const oaNoticeAttList = ref([]);

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = data?.isUpdate;
        radioValue.value = 'radioAll';
        fileList.value = [];
        oaNoticeAttList.value = [];

        initWindowFunc();

        if (unref(isUpdate)) {
          await getNoticeEdit({ id: data.record.id }).then((res) => {
            let notice = res.notice;
            oaNoticeAttList.value = notice.oaNoticeAttList || [];
            if (unref(oaNoticeAttList).length > 0) {
              setTableData(unref(oaNoticeAttList));
            }
            if (!res.names) {
              radioValue.value = 'radioAll';
            } else {
              radioValue.value = 'radioSelect';
            }
            dataRef = {
              ...notice,
              realNames: res.realNames ? res.realNames : '全部用户',
              receiver: res.names,
              level: notice.noticeLevel == 1,
              isReply: notice.isReply == 1,
              isShow: notice.isShow,
              isForcedResponse: notice.isForcedResponse == 1,
              isToMobile: notice.isToMobile == 1,
              color: data.record.color ? data.record.color : '#000000',
              isBold: data.record.isBold == 1,
              visualPath: res.visualPath,
            };
            updateSchema({
              field: 'realNames',
              required: false,
            });
            setFieldsValue({
              ...dataRef,
            });
          });
        } else {
          tempAttList = [];

          await getNoticeAdd().then((res) => {
            dataRef = {
              realNames: '全部用户',
              color: '#000000',
              unitCode: res.myUnitCode,
              userName: res.userName,
              beginDate: formatToDate(dateUtil()),
              visualPath: res.visualPath,
            };
          });
          updateSchema({
            field: 'realNames',
            required: true,
          });
          setFieldsValue({
            ...dataRef,
          });
        }
      });

      function initWindowFunc() {
        let newWindow = window as any;
        newWindow.reloadAttachment = reloadAttachment;
        newWindow.ajaxPost = ajaxPost;
        newWindow.myMsg = myMsg;
        newWindow.getServerInfo = getServerInfo;
        newWindow.setUploadFileTreeListAttInfo = setUploadFileTreeListAttInfo;
        newWindow.addTempAtt = addTempAtt;
        newWindow.delTempAtt = delTempAtt;
      }

      const columns: BasicColumn[] = [
        {
          title: '标题',
          dataIndex: 'name',
          align: 'left',
        },
        {
          title: '创建时间',
          dataIndex: 'uploadDate',
        },
      ];
      const [registerTable, { setTableData }] = useTable({
        title: '文件列表',
        api: '' as any,
        columns,
        formConfig: {},
        searchInfo: {
          op: 'search',
        },
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        immediate: false,
        pagination: false,
        canResize: false,
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });

      function handleDelete(record, index) {
        console.log('record', record);
        let params = {
          noticeId: dataRef.id,
          attId: record.id,
        };
        getNoticeDelAtt(params).then((res) => {
          console.log('res==>', res);
          oaNoticeAttList.value.splice(index, 1);
          setTableData(unref(oaNoticeAttList));
        });
      }

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      function getRadioValue(e) {
        if (e === 'radioAll') {
          setFieldsValue({
            realNames: '全部用户',
          });
        } else {
          selectUser();
        }
      }

      const [registerModal, { openModal }] = useModal();
      function selectUser() {
        openModal(true, {
          type: 'notice', //公告入口判断
        });
      }

      async function handleModelSuccess(data) {
        //选择用户后的回调
        let realNames = data.map((item) => item.realName);
        let receivers = data.map((item) => item.name);
        dataRef.receiver = receivers;
        setFieldsValue({
          realNames: realNames,
        });
      }
      async function handleSubmit() {
        if (
          !isUploadFinished(currentRoute.value?.query?.titleName || currentRoute.value?.meta?.title)
        ) {
          createMessage.warn('文件正在上传中，请在文件上传结束后再操作');
          return;
        }

        try {
          console.log('handleSubmit dataRef', dataRef);
          const values = await validate();
          let formData = Object.assign({}, dataRef, values);

          console.log('formData', formData);
          console.log('dataRef', dataRef);
          formData.level = formData.level == true ? 1 : 0;
          formData.isShow = formData.isShow == true ? 1 : 0;
          formData.isReply = formData.isReply == true ? 1 : 0;
          formData.isForcedResponse = formData.isForcedResponse == true ? 1 : 0;
          let params = {
            title: formData.title,
            color: formData.color,
            isShow: formData.isShow,
            isReply: formData.isReply,
            isToMobile: formData.isToMobile,
            content: formData.content,
            beginDate: formData.beginDate,
            endDate: formData.endDate ? formData.endDate : '',
            isNoticeMgr: formData.isNoticeMgr,
            userName: formData.userName,
            unitCode: formData.unitCode,
            isAll: radioValue.value == 'radioAll' ? 2 : 0,
            receiver: formData.receiver,
            att1: formData.att1, //文件  多个就是 att2,att3...
            isForcedResponse: formData.isForcedResponse,
            level: formData.level,
            isBold: formData.isBold ? 1 : 0,
          };

          // 如果启用了obs上传，则此处不需要再加入上传按钮所选的文件
          if (!isObjStoreEnabled.value) {
            if (fileList.value.length > 0) {
              fileList.value.forEach((file: UploadProps['fileList'][number], index) => {
                params[`att${index + 1}`] = file as any;
              });
            }
          }

          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          let Files = new FormData();
          if (!unref(isUpdate)) {
            for (let v in params) {
              Files.append(v, params[v]);
            }
            for (let k in tempAttList) {
              Files.append('tempIds', tempAttList[k]);
            }
            await getNoticeCreate(Files);
          } else {
            params.id = formData.id;
            console.log('params', params);
            for (let v in params) {
              Files.append(v, params[v]);
            }
            await getNoticeSave(Files);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      function getColor(e, node) {
        console.log('getColor', e, node);
      }

      const handleRemove: UploadProps['onRemove'] = (file) => {
        const index = fileList.value.indexOf(file);
        const newFileList = fileList.value.slice();
        newFileList.splice(index, 1);
        fileList.value = newFileList;
      };

      const beforeUpload: UploadProps['beforeUpload'] = (file) => {
        fileList.value = [...fileList.value, file];
        return false;
      };

      const handleUpload = () => {
        // const formData = new FormData();
        // fileList.value.forEach((file: UploadProps['fileList'][number]) => {
        //   formData.append('files[]', file as any);
        // });
      };

      function handleDownload(record: any) {
        if (serverInfo.isObjStoreEnabled) {
          getObjectByKey(record.visualPath + '/' + record.diskName, record.name);
        } else {
          record.isDownloadAtt = true;
          const params = {
            visitKey: record.visitKey,
            attachId: record.id,
          };
          console.log('reocrd.name', record.name);
          getNoticeAttDownload(params)
            .then((data) => {
              if (data) {
                downloadByData(data, `${record.name}`);
              }
            })
            .finally(() => {
              record.isDownloadAtt = false;
            });
        }
      }

      const handleDownloadObsFile = (key, fileName) => {
        getObjectByKey(key, fileName);
      };

      let fileNo = 0;
      //获取文件change事件
      const handleFilesChange = (info) => {
        console.log('info', info);
        const { file } = info;

        let fileName = file.name;
        uploadFileObjectFunc({
          files: [file],
          formName: '',
          route: currentRoute.value,
          fieldName: 'attNotice' + fileNo,
          filePath: dataRef.visualPath,
          formCode: '',
          pageType: isUpdate.value ? 'noticeEdit' : 'noticeAdd',
          mainId: dataRef.id,
          fieldTitle: '附件',
        });

        fileNo++;
      };

      const handleRemoveFile = (file, actions) => {
        console.log('handleRemoveFile', file);
        let treeList = uploadFileStore.getUploadFileTreeList;
        treeList.forEach((item) => {
          item.children.forEach((it) => {
            console.log('handleRemoveFile it', it);
            if (it.file.uid === file.uid) {
              if (it.progress == 100) {
                if (unref(isUpdate)) {
                  let params = {
                    noticeId: dataRef.id,
                    attId: it.attId,
                  };
                  getNoticeDelAtt(params).then((res) => {
                    console.log('res==>', res);
                    deleteByUid(file.uid);
                    let k = 0,
                      index = -1;
                    oaNoticeAttList.value.forEach((item: any) => {
                      if (item.id == it.attId) {
                        index = k;
                      }
                      k++;
                    });
                    if (index != -1) {
                      oaNoticeAttList.value.splice(index, 1);
                      setTableData(unref(oaNoticeAttList));
                    } else {
                      console.error('Notice attachment: ' + it.id + ' is not found.');
                    }
                  });
                } else {
                  deleteByUid(file.uid);
                  delTempAtt(it.attId);
                }
              } else {
                deleteByUid(file.uid);
                actions.remove();
              }
            }
          });
        });
      };

      const uploadFileStore = useUploadFileStore();
      const getProgress = computed(() => (file: any) => {
        console.log('file', file);
        let treeList = uploadFileStore.getUploadFileTreeList;
        let progress = 100;
        treeList.forEach((item) => {
          item.children.forEach((it) => {
            console.log('it', it);
            if (it.file.uid === file.uid) {
              progress = it.progress;
              if (progress == 100) {
                if (unref(isUpdate)) {
                  // reloadAttachment();
                }
              }
            }
          });
        });
        return progress;
      });

      const getAttVisible = computed(() => (file: any) => {
        let treeList = uploadFileStore.getUploadFileTreeList;
        let isFound = false;
        treeList.forEach((item) => {
          item.children.forEach((it) => {
            console.log('it', it);
            if (it.file.uid === file.uid && it.progress < 100 && !it.attId) {
              isFound = true;
            }
          });
        });
        // 未找到，说明是从树形列表上删除了该节点
        return isFound;
      });

      const getAttUploadFinished = computed(() => (file: any) => {
        let treeList = uploadFileStore.getUploadFileTreeList;
        let progress = 0;
        let isFound = false;
        treeList.forEach((item) => {
          item.children.forEach((it) => {
            console.log('it', it);
            if (it.file.uid === file.uid) {
              progress = it.progress;
              isFound = true;
            }
          });
        });
        // 未找到，说明是从树形列表上删除了该节点
        if (!isFound) {
          return true;
        }
        if (progress == 100) {
          return true;
        }
      });

      const reloadAttachment = async () => {
        let params = {
          id: dataRef.id,
        };
        let list = await getNoticeAttList(params);
        oaNoticeAttList.value = list;
        setTableData(list);
      };

      const handlePreviewAtt = computed(() => (file: any) => {
        let previewUrl = '';
        let treeList = uploadFileStore.getUploadFileTreeList;
        treeList.forEach((item) => {
          item.children.forEach((it) => {
            console.log('it', it);
            if (it.file.uid === file.uid) {
              previewUrl = it.previewUrl;
            }
          });
        });

        window.open(previewUrl);
      });

      const handleDownloadAtt = computed(() => (file: any) => {
        let key = '';
        let treeList = uploadFileStore.getUploadFileTreeList;
        treeList.forEach((item) => {
          item.children.forEach((it) => {
            if (it.file.uid === file.uid) {
              console.log('handleDownloadAtt it', it);
              key = it.fieldValue;
              handleDownloadObsFile(key, file.name);
            }
          });
        });
      });

      const setUploadFileTreeListAttInfo = (file: any, attId, canPreview, previewUrl, visitKey) => {
        let treeList = uploadFileStore.getUploadFileTreeList;
        treeList.forEach((item) => {
          item.children.forEach((it) => {
            console.log('setUploadFileTreeListAttInfo it', it);
            console.log('setUploadFileTreeListAttInfo file.uid', file.uid);
            if (it.file.uid === file.uid) {
              it.attId = attId;
              it.canPreview = canPreview;
              it.previewUrl = previewUrl;
              it.visitKey = visitKey;

              console.log('setUploadFileTreeListAttInfo it2', it);
              uploadFileStore.setUploadFileTreeList(treeList);
            }
          });
        });
      };

      const addTempAtt = (id: number) => {
        tempAttList.push(id);
        console.log('addTempAtt', id, tempAttList);
      };

      const delTempAtt = (id) => {
        console.log('delTempAtt', id, tempAttList);
        let arr = tempAttList.filter((item) => item !== id);
        tempAttList = arr;
        console.log('delTempAtt2', id, tempAttList);
      };

      return {
        registerDrawer,
        registerForm,
        getTitle,
        radioValue,
        handleSubmit,
        registerModal,
        selectUser,
        handleModelSuccess,
        getRadioValue,
        gradientColor,
        handleRemove,
        beforeUpload,
        handleUpload,
        fileList,
        getColor,
        registerTable,
        handleDelete,
        oaNoticeAttList,
        isUpdate,
        handleDownload,
        handleDownloadObsFile,
        handleFilesChange,
        handleRemoveFile,
        getProgress,
        getAttUploadFinished,
        handleDownloadAtt,
        isObjStoreEnabled,
        handlePreviewAtt,
        getAttVisible,
      };
    },
  });
</script>
